package cn.school.prevention.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.school.classManage.vo.SchoolClassVO;
import cn.school.common.utils.StringUtils;
import cn.school.common.utils.SysUserUtils;
import cn.school.notice.dao.SchoolNoticeDao;
import cn.school.prevention.dao.FeedBackDao;
import cn.school.prevention.dao.InfoDao;
import cn.school.prevention.dao.ScopeDao;
import cn.school.prevention.entity.FeedBack;
import cn.school.prevention.entity.Info;
import cn.school.prevention.entity.Scope;
import cn.school.prevention.service.InfoService;
import cn.school.student.dao.StudentInfoDao;
import cn.school.student.entity.StudentInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class InfoServiceImpl extends ServiceImpl<InfoDao, Info> implements InfoService {

    @Autowired
    private InfoDao infoDao;

    @Autowired
    private SchoolNoticeDao schoolNoticeDao;

    @Autowired
    private StudentInfoDao studentInfoDao;

    @Autowired
    ScopeDao scopeDao;

    @Autowired
    FeedBackDao feedBackDao;


    @Override
    public int deleteInfo(Info info) {
        int i = infoDao.deleteById(info.getId());
        return i;
    }

    /**
     * 新增任务
     *
     * @param info
     * @param flag true ：来源为定时任务  false：来源为页面新增
     * @return
     */
    @Override
    public int insert(Info info, boolean flag) {

        List<SchoolClassVO> classList = null;
        Scope scope = null;
        FeedBack feedBack = null;
        LambdaQueryWrapper<StudentInfo> wrapper = null;
        List<Info> infos = null;
        String todoDate = null;
        //检查当前时间是否包含在任务时间内，如果包含则取当前时间，如果不包含则取任务开始时间
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            //cl.getBeginDate()为当前日期字符串
            Date date2 = formatter.parse(info.getBeginDate());
            //formatter.format(date)为服务器获取的字符串
            Date date3 = formatter.parse(formatter.format(date));
            int i = date2.compareTo(date3);
            if (i == 1) {
                todoDate = info.getBeginDate();
            } else {
                todoDate = DateUtil.formatDate(new Date());
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        int insert = 0;
        if (!flag) {
            insert = saveInfoData(info);
        }
        if (insert > 0 || flag) {
            if (info.getScope().equals("1")) {
                classList = schoolNoticeDao.findSchoolClassByClassId(info.getClassIds());
                for (SchoolClassVO classVO : classList) {
                    scope = new Scope();
                    scope.setStatus("1");
                    scope.setPiId(info.getId() + "");
                    scope.setTeacherId(classVO.getClassTeacherId());
                    scope.setClassId(classVO.getId() + "");
                    scope.setTodoFeedbackDate(todoDate);
                    scopeDao.insert(scope);
                    wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(StudentInfo::getClassId, classVO.getId());
                    wrapper.eq(StudentInfo::getStatus, 1);
                    List<StudentInfo> studentList = studentInfoDao.selectList(wrapper);
                    for (StudentInfo stInfo : studentList) {
                        feedBack = new FeedBack();
                        feedBack.setTodoFeedbackDate(todoDate);
                        feedBack.setStudentId(stInfo.getStudentId());
                        feedBack.setClassId(stInfo.getClassId() + "");
                        feedBack.setStudentName(stInfo.getName());
                        feedBack.setScopeId(scope.getId() + "");
                        feedBack.setStatus("1");
                        feedBackDao.insert(feedBack);
                    }
                }

            } else if (info.getScope().equals("2")) {
                classList = schoolNoticeDao.findSchoolClassByGrade(info.getGradeId(), SysUserUtils.getSysUser().getTenantId());
                for (SchoolClassVO classVO : classList) {
                    scope = new Scope();
                    scope.setStatus("1");
                    scope.setPiId(info.getId() + "");
                    scope.setTeacherId(classVO.getClassTeacherId());
                    scope.setClassId(classVO.getId() + "");
                    scope.setTodoFeedbackDate(todoDate);
                    scopeDao.insert(scope);
                    wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(StudentInfo::getClassId, classVO.getId());
                    wrapper.eq(StudentInfo::getStatus, 1);
                    List<StudentInfo> studentList = studentInfoDao.selectList(wrapper);
                    for (StudentInfo stInfo : studentList) {
                        feedBack = new FeedBack();
                        feedBack.setStudentId(stInfo.getStudentId());
                        feedBack.setClassId(stInfo.getClassId() + "");
                        feedBack.setStudentName(stInfo.getName());
                        feedBack.setScopeId(stInfo.getId() + "");
                        feedBack.setStatus("1");
                        feedBack.setTodoFeedbackDate(todoDate);
                        feedBackDao.insert(feedBack);
                    }
                }
            } else if (info.getScope().equals("3")) {
                classList = schoolNoticeDao.findSchoolClassAll(SysUserUtils.getSysUser().getTenantId());
                for (SchoolClassVO classVO : classList) {
                    scope = new Scope();
                    scope.setStatus("1");
                    scope.setPiId(info.getId() + "");
                    scope.setTeacherId(classVO.getClassTeacherId());
                    scope.setClassId(classVO.getId() + "");
                    scope.setTodoFeedbackDate(todoDate);
                    scopeDao.insert(scope);
                    wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(StudentInfo::getClassId, classVO.getId());
                    wrapper.eq(StudentInfo::getStatus, 1);
                    List<StudentInfo> studentList = studentInfoDao.selectList(wrapper);
                    for (StudentInfo stInfo : studentList) {
                        feedBack = new FeedBack();
                        feedBack.setStudentId(stInfo.getStudentId());
                        feedBack.setClassId(stInfo.getClassId() + "");
                        feedBack.setStudentName(stInfo.getName());
                        feedBack.setScopeId(stInfo.getId() + "");
                        feedBack.setStatus("1");
                        feedBack.setTodoFeedbackDate(todoDate);
                        feedBackDao.insert(feedBack);
                    }
                }
            }
            return 1;
        } else {
            return -1;
        }
    }

    private int saveInfoData(Info info) {
        String userName = SysUserUtils.getSysUser().getUsername();
        info.setCreateBy(userName);
        info.setCreateTime(new Date());
        info.setStatus("1");
        // 123,123,123
        info.setClassId(org.apache.commons.lang.StringUtils.join(info.getClassIds(), ","));
        int insert = infoDao.insert(info);
        return insert;
    }


    @Override
    public int update(Info info) {
        return infoDao.updateById(info);
    }

    @Override
    public IPage<Info> infoPageList(Info info) {
        LambdaQueryWrapper<Info> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!StringUtils.isEmpty(info.getTitle()), Info::getTitle, info.getTitle());
        wrapper.le(!StringUtils.isEmpty(info.getBeginDate()), Info::getBeginDate, info.getBeginDate());
        wrapper.ge(!StringUtils.isEmpty(info.getBeginDate()), Info::getEndDate, info.getBeginDate());
        wrapper.eq(!StringUtils.isEmpty(info.getStatus()), Info::getStatus, info.getStatus());
        //租户
        wrapper.eq(Info::getTenantId,SysUserUtils.getSysUser().getTenantId());
        wrapper.orderByDesc(Info::getId);
        IPage<Info> page = page(new Page<>(info.getPageNum(), info.getPageSize()), wrapper);
        return page;
    }

    @Override
    public int delete(Info info) {
     try{
        infoDao.deleteByPrimaryKey(info);
             return 1;
     }catch (Exception e) {
         return 0;
     }
    }


}
